package com.csjung.games.gamenori.client.presenter;

import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

import com.csjung.games.gamenori.client.event.UserListRefreshEvent;
import com.csjung.games.gamenori.client.ui.DestopUserList;
import com.csjung.games.gamenori.shared.GamenoriRequestFactory;
import com.csjung.games.gamenori.shared.UserProxy;
import com.csjung.games.gamenori.shared.UserServiceRequest;
import com.csjung.games.ui.client.PresentsWidgets;

import java.util.List;

/**
 * Activity that presents a list of users.
 */
public class UserListPresenter implements PresentsWidgets {

  private DestopUserList destopUserList;
  
  private final GamenoriRequestFactory requestFactory;
  
  public UserListPresenter(DestopUserList destopUserList, GamenoriRequestFactory requestFactory) {
    this.destopUserList = destopUserList;
    this.requestFactory = requestFactory;
  }
  
  @Override
  public String mayStop() {
    return null; // always happy to stop
  }

  @Override
  public void start(EventBus eventBus) {
    
    eventBus.addHandler(UserListRefreshEvent.TYPE, new UserListRefreshEvent.Handler() {
      public void onUserListRefresh(UserListRefreshEvent event) {
        refreshUserList();
      }
    });
  }

  @Override
  public void stop() {
    // TODO Auto-generated method stub
    
  }

  @Override
  public Widget asWidget() {
    return destopUserList;
  }

  public void selectUser(List<UserProxy> users) {
    destopUserList.setUsers(users);
  }
  
  private void refreshUserList() {
    destopUserList.clearList();
    UserServiceRequest request = requestFactory.userServiceRequest();
    request.getAllUsers().to(new Receiver<List<UserProxy>>() {
      @Override
      public void onSuccess(List<UserProxy> response) {
        selectUser(response);
      }
      @Override
      public void onFailure(ServerFailure error) {
        super.onFailure(error);
      }
      
    });
    request.fire();
  }
}
